package com.open.capacity.utils;

import com.open.capacity.utils.sequence.DbSeqBuilder;
import com.open.capacity.utils.sequence.sequence.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * Created by fengtangquan on 2019/4/15.
 */
@Component
public class IdGenerator {


    private static DataSource dataSource;

    private static Environment env;

    @Autowired
    public void setLettuceConnectionFactory(DataSource dataSource, Environment env) {
        IdGenerator.dataSource = dataSource;
        IdGenerator.env = env;
    }

    public static String next(String bizName,int length) {
//        String code;
//        Sequence sequence = RedisSeqBuilder.create()
//                .bizName(bizName)
//                .step(1)
//                .stepStart(10000)
//                .build();
//        Long seq;
//        try {
//            seq = sequence.nextValue();
//            code = String.valueOf(DateUtil.dateTimeNow() + "" + seq);
//        } catch (Exception ex) {
//            sequence = DbSeqBuilder.create().bizName(bizName).step(1).stepStart(10000).build();
//            seq = sequence.nextValue();
//            code = String.valueOf(DateUtil.dateTimeNow() + "" + seq);
//        }

        Sequence sequence = DbSeqBuilder.create().dataSource(dataSource).bizName(bizName).step(1).stepStart(0).build(env);
        Long seq = sequence.nextValue();
        String code = String.valueOf(seq);
        String nextCode = StringUtil.getNextSequence(code,length);
        return nextCode;
    }
}
